<template>
  <div>
    <el-form inline :model="queryPost" ref="postQueryFormRef">
      <el-form-item>
        <el-input placeholder="关键字" v-model="queryPost.keywords"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryPost.status" placeholder="状态" style="width: 240px">
          <el-option label="全部" :value="-1"/>
          <el-option label="正常" :value="0"/>
          <el-option label="禁用" :value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getSocPostList">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" @click="postQueryFormRef?.resetFields()"
        >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-button :icon="Plus" type="primary" @click="dialogVisible = true" size="small"
    >新增
    </el-button>
    <el-table :data="postPage.list" border="parentBorder" v-loading="loading">
      <el-table-column type="expand">
        <template #default="props">
          <div m="4">
            <p m="t-0 b-2">点赞数: {{ props.row.likes }}</p>
            <p m="t-0 b-2">创建时间: {{ props.row.createdTime }}</p>
            <p m="t-0 b-2">修改时间: {{ props.row.updateTime }}</p>
            <p m="t-0 b-2">简介: {{ props.row.synopsis }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="postId" label="编号"/>
      <el-table-column prop="userId" label="用户编号"/>
      <el-table-column prop="bardId" label="吧编号"/>
      <el-table-column prop="schoolId" label="校园编号"/>
      <el-table-column prop="title" label="标题"/>
      <el-table-column prop="content" label="内容"/>
      <el-table-column prop="postRange" label="范围"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button @click="openModify(scope.row.postId)" :icon="EditPen" size="small" type="warning">
            修改
          </el-button>
          <el-divider direction="vertical"/>
          <el-button @click="openDel(scope.row.postId)" type="danger" :icon="Delete" size="small">删除</el-button>
          <el-divider direction="vertical"/>
          <el-dropdown>
            <el-button size="small" class="el-dropdown-link">
              更多
              <el-icon :size="14" class="el-icon--right">
                <ArrowDown/>
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openReplies(scope.row.postId)"
                >评论
                </el-dropdown-item
                >
                <el-dropdown-item>Action 2</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="queryPost.pageNum"
        :page-sizes="[8, 16, 32, 64]"
        v-model:page-size="queryPost.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="postPage.total"
    />
    <el-dialog
        :title="isAdd ? '新增' : '修改'"
        v-model="dialogVisible"
        width="700"
        @close="socPostFormRef?.resetFields"
    >
      <el-form :model="socPost" ref="socPostFormRef" :rules="rules" label-width="80" inline>
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="socPost.userId"></el-input>
        </el-form-item>
        <el-form-item label="校园编号" prop="schoolId">
          <el-input v-model="socPost.schoolId"></el-input>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="socPost.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="socPost.content"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="synopsis">
          <el-input type="textarea" v-model="socPost.synopsis"></el-input>
        </el-form-item>
        <el-form-item label="媒体内容" prop="uploadFileList">
          <UploadButton url="/post" :limit="10" @filePath="uploadSuccess"></UploadButton>
        </el-form-item>
        <el-form-item label="范围" prop="postRange">
          <el-input v-model="socPost.postRange"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="socPost.status"></el-input>
        </el-form-item>

        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker
              v-model="socPost.createdTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="修改时间" prop="updateTime">
          <el-date-picker
              v-model="socPost.updateTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSocPost(socPostFormRef)">保存</el-button>
      </span>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="帖子评论" direction="rtl">
      <el-row v-for="item in postRepliesPage.list" class="border" v-show="postRepliesPage.list">
        <el-col :span="6">
          <el-avatar :src="item.avatar"></el-avatar>
          <p>{{ item.userName }}</p>
        </el-col>
        <el-col :span="18">
          {{ item.content }}
        </el-col>
      </el-row>
      <div v-show="!postRepliesPage.list">
        <el-empty description="暂无评论"/>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, watch} from "vue";
import {useRoute} from "vue-router";
import {Search, Refresh, Delete, EditPen, Plus, ArrowDown} from "@element-plus/icons-vue";
import type {FormInstance, FormRules} from "element-plus";
import {ElMessage, ElMessageBox} from "element-plus";
import type {SocPost, SocPostCreateDTO} from "@/api/social/post/type";
import {
  reqCreatePost,
  reqUpdatePost,
  reqGetPostPage,
  reqGetPostById,
  reqDeletePostById,
  reqGetPostRepliesPage,
} from "@/api/social/post";
import UploadButton from "@/components/common/UploadButton.vue";
import type {SocPostReplies} from "@/api/social/post/type";

let queryPost = reactive({
  pageNum: 1,
  pageSize: 8,
  keywords: "",
  status: -1,
});

let socPost = reactive<SocPostCreateDTO>({
  postId: null,
  userId: "",
  bardId: "",
  schoolId: "",
  title: "",
  content: "",
  postRange: 0,
  status: 0,
  synopsis: "",
  likes: 0,
  createdTime: null,
  updateTime: null,
  uploadFileList: [],
  tags: [],
});
let postRepliesQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  postId: "",
});
let rules = reactive<FormRules<SocPost>>({
  schoolId: [
    {
      required: true,
      message: "请输入校园编号",
      trigger: "blur",
    },
  ],
  title: [
    {
      required: true,
      message: "请输入标题",
      trigger: "blur",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入内容",
      trigger: "blur",
    },
  ],
});
const route = useRoute();
let dialogVisible = ref(false);
let loading = ref<boolean>(true);
let isAdd = ref(true);
let drawer = ref(false);
let socPostFormRef = ref<FormInstance>();
let postQueryFormRef = ref<FormInstance>();
let postPage = reactive({
  total: 0,
  list: [] as SocPost[],
  pageNum: 0,
});
let postRepliesPage = reactive({
  total: 0,
  list: [] as SocPostReplies[],
  pageNum: 0,
});

let getSocPostList = () => {
  reqGetPostPage(queryPost).then((res) => {
    Object.assign(postPage, res.data);
    loading.value = false;
  });
};
let getSocPostReplies = (postId: string) => {
  postRepliesQuery.postId = postId;
  reqGetPostRepliesPage(postRepliesQuery).then((res) => {
    postRepliesPage.list = res.data.list;
    postRepliesPage.total = res.data.total;
  });
};
let openModify = (postId: string) => {
  reqGetPostById(postId).then((res) => {
    Object.assign(socPost, res.data);
    isAdd.value = false;
    dialogVisible.value = true;
  });
};
let openReplies = (postId: string) => {
  getSocPostReplies(postId);
  drawer.value = true;
};

let uploadSuccess = (filePath: string) => {
  socPost.uploadFileList.push(filePath);
};

let submitSocPost = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        await reqCreatePost(socPost);
      } else {
        await reqUpdatePost(socPost);
        isAdd.value = true;
      }
      await getSocPostList();
      dialogVisible.value = false;
    } else console.log("error submit!", fields);
  });
};

let openDel = (postId: string) => {
  ElMessageBox.confirm("删除帖子后不能恢复，是否删除？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeletePostById(postId).then(() => {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          getSocPostList();
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
};

onMounted(() => {
  getSocPostList();
  // 如果是从贴吧管理中点击发帖跳转过来的，就自动打开弹窗
  if (route.query.bardId) {
    socPost.bardId = route.query.bardId as string;
    dialogVisible.value = true;
  }
});
watch([() => queryPost.pageNum, () => queryPost.pageSize], () => {
  getSocPostList();
});
</script>
<style scoped>
.border {
  color: var(--el-text-color-regular);
  border: 1px solid var(--el-border-color);
  border-radius: 0;
}
</style>
